import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:simple_logger/simple_logger.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';
import 'package:wk_robot2/generated/RTAVParams.pb.dart';

import '../../../logger/Logger.dart';
import '../../../utils/CommonUtil.dart';
import '../../../widget/CommonWidgets.dart';

class VideoLiveManager{
  String TAG = "VideoLiveManager";
  final int SDK_APPID = 1600051692;
  late TRTCCloud trtcCloud;
  Function(String userId) _onUserVideoAvailable = (userId){};
  Function() _onRemoteUserLeaveRoom = (){};
  Function() _onConnectionLost = (){};
  Function() _onConnectionAvailable = (){};


  init() async {
    // 创建 TRTCCloud 单例
    trtcCloud = (await TRTCCloud.sharedInstance())!;
// 注册 TRTC 事件回调
    trtcCloud.registerListener(onRtcListener);


    }

  enterRoom({required RTAVUserInfo userInfo, required RTAVRoomInfo roomInfo,
      required void Function(String userId) onUserVideoAvailable,
      required Function() onRemoteUserLeaveRoom,
      required Function() onConnectionLost,
      required Function() onConnectionAvailable,
  }
      ) async {
    // 如果您的场景为“互动视频直播”，请将场景设置为 TRTC_APP_SCENE_LIVE，并在TRTCParams中为role字段设置相应的值。
    _onUserVideoAvailable = onUserVideoAvailable;
    _onRemoteUserLeaveRoom = onRemoteUserLeaveRoom;
    _onConnectionLost = onConnectionLost;
    _onConnectionAvailable = onConnectionAvailable;
    await trtcCloud.enterRoom(
    TRTCParams(
    sdkAppId: SDK_APPID,
    userId: userInfo.userId,
    userSig: userInfo.sig,
    role: TRTCCloudDef.TRTCRoleAnchor,
    roomId: roomInfo.roomId,
    strRoomId: roomInfo.privateMapKey),
    TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);
    _startHeartBeatTimer();

  }

  void setMicState(bool isEnable){
    trtcCloud.muteLocalAudio(!isEnable);
    if(isEnable) {
      trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);
    }else{
      trtcCloud.stopLocalAudio();
    }
  }

  Future<void> startRemoteView(String userId, int? viewId) async {
    if(viewId == null){
      return;
    }
    // 播放 denny 的摄像头画面（我们称之为“主路画面”）
    trtcCloud.startRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, viewId);
  }

  void exitRoom(){
    trtcCloud.exitRoom();
    _cancelHeartBeatTimer();
    _onUserVideoAvailable = (userId){};
    _onRemoteUserLeaveRoom = (){};
  }

  TRTCCloudListener? _currentStatus;
  void onRtcListener(type, param) async {
    if(type != TRTCCloudListener.onNetworkQuality && type != TRTCCloudListener.onStatistics) {
      logger.info("$TAG onRtcListener: $type, $param");
    }
    _currentStatus = type;
    if (type == TRTCCloudListener.onError) {
      if (param['errCode'] == -1308) {
        print('$TAG, Failed to start screen recording');
      } else {
        print("$TAG, ${param['errMsg']}");
      }
    }else if (type == TRTCCloudListener.onEnterRoom) {
      if (param > 0) {
        print('$TAG,  Enter room success');
      }
    }else if(type == TRTCCloudListener.onUserVideoAvailable){
      if(param["available"] == true){
        _onUserVideoAvailable(param["userId"]);
      }else if(param["available"] == false){
        // todo 退出
      }

    }else if(type == TRTCCloudListener.onRemoteUserLeaveRoom){
      _onRemoteUserLeaveRoom();
    }else if(type == TRTCCloudListener.onConnectionLost){
      _onConnectionLost();
    }else if(type == TRTCCloudListener.onConnectionRecovery){
      _onConnectionAvailable();
    }
  }

  Timer? _timer;
  int HEART_CMD_ID = 10086;
  // 启动定时器
  void _startHeartBeatTimer() {
    _timer = Timer.periodic(Duration(seconds: 5), (Timer timer) {
      trtcCloud.sendCustomCmdMsg(HEART_CMD_ID,  CommonUtil.getLoginUserId().toString(), false, false);
      //logger.info("$TAG, send HEART_CMD_ID");
    });
  }

  void _cancelHeartBeatTimer(){
    _timer?.cancel();
  }
}